<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\User;
use App\Models\UserTier;
use Illuminate\Http\Request;

class TierController extends Controller
{
    /**
     * 获取用户段位信息
     */
    public function show(User $user)
    {
        $tier = UserTier::where('user_id', $user->id)->first();

        if (!$tier) {
            // 创建初始段位
            $tier = UserTier::create([
                'user_id' => $user->id,
                'current_tier' => 'bronze',
                'tier_points' => 0
            ]);
        }

        return response()->json($tier);
    }

    /**
     * 尝试升级段位
     */
    public function upgrade(User $user)
    {
        // 确保只能升级自己的段位
        if ($user->id !== auth()->id()) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }

        $tier = UserTier::where('user_id', $user->id)->first();

        if (!$tier) {
            return response()->json(['error' => 'Tier not found'], 404);
        }

        // 段位升级逻辑
        $tierLevels = ['bronze', 'silver', 'gold', 'platinum', 'diamond'];
        $currentIndex = array_search($tier->current_tier, $tierLevels);
        $requiredPoints = ($currentIndex + 1) * 1000; // 每个段位需要的积分

        if ($tier->tier_points >= $requiredPoints && $currentIndex < count($tierLevels) - 1) {
            $tier->update([
                'current_tier' => $tierLevels[$currentIndex + 1],
                'tier_points' => $tier->tier_points - $requiredPoints
            ]);

            return response()->json([
                'tier' => $tier,
                'message' => 'Tier upgraded successfully'
            ]);
        }

        return response()->json([
            'error' => 'Insufficient points for upgrade',
            'required_points' => $requiredPoints,
            'current_points' => $tier->tier_points
        ], 400);
    }
}